﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator
{
    public partial class Generator : Form
    {
        List<Table> tables = null;

        public Generator()
        {
            InitializeComponent();
        }

        private void Generator_Load(object sender, EventArgs e)
        {
            List<string> servers = new List<string>();
            servers.Add("Select One");
            servers.AddRange(Utility.SqlServers);
            cmbServers.DataSource = servers;

            LoadDatabase();
        }

        private void LoadDatabase()
        {
            if (cmbServers.SelectedValue.ToString() != "Select One")
            {
                List<string> databases = new List<string>();
                databases.Add("Select One");
                databases.AddRange(Utility.Databases(cmbServers.SelectedValue.ToString()));

                cmbDatabases.DataSource = databases;
            }
        }

        private void cmbServers_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDatabase();
        }

        private void cmbDatabases_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cmbDatabases.SelectedValue.ToString() != "Select One")
                tables = Utility.Tables(cmbServers.SelectedValue.ToString(), cmbDatabases.SelectedValue.ToString()); 
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            bool result = true;

            foreach (Table table in tables)
            {
                string text = Utility.ReadTemplate("~/templates/ORM.txt");
                result &= Utility.ModifyORMTemplate(text, table, tbxNamespace.Text);

                
            }

            string text2 = Utility.ReadTemplate("~/templates/StoredProcedures.txt");
            result &= Utility.ModifySPTemplate(text2);

            result &= Utility.ModifyPageTemplates(tbxNamespace.Text);

            if( result)
                lblMessage.Text = "Done";
        }
    }
}
